package com.hmyd.hmyd_android.ui;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.crypto.Crypto;
import com.hmyd.hmyd_android.dialog.NormalDialog;
import com.hmyd.hmyd_android.dialog.NormalDialogListener;
import com.hmyd.hmyd_android.dto.AppSystem;
import com.hmyd.hmyd_android.dto.CurrentTimeMillis;
import com.hmyd.hmyd_android.dto.Key;
import com.hmyd.hmyd_android.dto.User;
import com.hmyd.hmyd_android.dto.Version;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.PreferencesUtils;
import com.hmyd.hmyd_android.utils.Utils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;

/**
 * 闪屏页
 * 
 * @author sun_t
 * 
 */
@ContentView(R.layout.activity_splash)
public class SplashScreenActivity extends BasicActivity {
	private final int LOGIN = 1;
	private final int CURRENTTIMEMILLIS = 3;// 获取服务器当前时间
	private final int KEY = 4;// 获取密匙
	private final int ROOT = 5;// 系统配置
	private final int GETLASTVERSION = 6;// 检查版本
	private String mobile;
	private String pwd;

	/**
	 * 是否是第一启动应用
	 */
	private boolean isFirstIn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Utils.isPrintMessage(false);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		onRequest(CURRENTTIMEMILLIS, UrlConstant.CURRENTTIMEMILLIS, HttpMethod.GET, null);
	}

	/**
	 * 发送数据请求
	 */
	/*public void onRequest() {
		onRequest(CURRENTTIMEMILLIS, UrlConstant.CURRENTTIMEMILLIS, HttpMethod.GET, null);
	}*/

	/**
	 * 请求成功
	 * 
	 * @param postId
	 *            请求通道ID
	 * @param msg
	 *            成功返回数据
	 */
	@Override
	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();
		switch (postId) {
		case CURRENTTIMEMILLIS:
			try {
				java.lang.reflect.Type currentTimeMillisType = new TypeToken<CurrentTimeMillis>() {
				}.getType();
				CurrentTimeMillis currentTimeMillis = gson.fromJson(result, currentTimeMillisType);
				
				PreferencesUtils.putLong(this, PreferencesUtils.TIMEDIFFERENCE,
						currentTimeMillis.timeMillis - System.currentTimeMillis());
				AppBasic.key  = null; 
				onRequest(KEY, UrlConstant.KEY, HttpMethod.GET, null);
			} catch (Exception e) {
				e.printStackTrace();
				MyToast.showHMToast(this, false, "检查当前网络连接！");
				if (!TextUtils.isEmpty(result) && result.toUpperCase().contains("<html>".toUpperCase())) {
					Utils.jumpURL(this, result, null, null, false);
				}
			}

			break;

		case KEY:
			java.lang.reflect.Type keyType = new TypeToken<Key>() {
			}.getType();
			Key key = gson.fromJson(result, keyType);

			AppBasic.key = Utils.getSignDecrypt(this, key.key);
			isFirstIn = PreferencesUtils.getBoolean(SplashScreenActivity.this,
					PreferencesUtils.getIsFirstInApp(getApplicationContext()), true);

			login();
			
			break;

		case LOGIN:
			java.lang.reflect.Type type2 = new TypeToken<User>() {
			}.getType();
			User user = gson.fromJson(result, type2);

			AppBasic.isLogin = true;
			AppBasic.isCheckIned = user.isCheckIned;
			AppBasic.totalScore = user.score;
			AppBasic.rewardScore = user.rewardScore;
			AppBasic.nextTimeScore = user.nextTimeScore;
			AppBasic.certNo = user.certNo;
			AppBasic.realName = user.realName;
			AppBasic.avatar = user.avatar;
			AppBasic.username = user.username;
			AppBasic.nickname = user.nickname;
			AppBasic.urlToken = user.urlToken;
			AppBasic.securityLevel = user.securityLevel;
			AppBasic.isSetSecurityCode = user.isSetSecurityCode;
			AppBasic.tel = user.tel;
			AppBasic.email = user.email;
			AppBasic.isVerifiedEmail = user.isVerifiedEmail;
			AppBasic.isSetSecurityQuestion = user.isSetSecurityQuestion;
			AppBasic.unReadMessageCount = user.unReadMessageCount;
			
			getRoot();
			checkVersion();
			break;
		case ROOT:
			java.lang.reflect.Type systemType = new TypeToken<AppSystem>() {
			}.getType();
			AppSystem system = gson.fromJson(result, systemType);
			if (system != null && system.sys != null && system.sys.app != null) {
				AppBasic.app = system.sys.app;
			}
			break;
		case GETLASTVERSION:
			java.lang.reflect.Type versionType = new TypeToken<Version>() {
			}.getType();
			AppBasic.version = gson.fromJson(result, versionType);
			if (AppBasic.version  != null && AppBasic.version.hasNew) {
				NormalDialog cd = new NormalDialog(this, R.style.calculatorDialog,
						new NormalDialogListener() {
							@Override
							public void ok() {
								Utils.jumpExplorer(SplashScreenActivity.this, AppBasic.version.newVersionUrl);
							}

							@Override
							public void cancle() {
								gotoMain();
							}
							
							@Override
							public void closed() {
								gotoMain();
							}

						}, AppBasic.version.infoTitle, AppBasic.version.info, "", "");
				cd.show();
			} else {
				gotoMain();
			}

			break;
		default:
			break;
		}
	}

	/**
	 * 请求失败
	 * 
	 * @param postId
	 *            请求通道ID
	 * @param msg
	 *            失败返回数据
	 */
	@Override
	public void onPostFailure(int postId, String msg) {
		if(postId == LOGIN) {
			// 登录验证失败，则显示错误信息，并继续进入应用
			MyToast.showHMToast(SplashScreenActivity.this, false, msg);
			getRoot();
			checkVersion();
		} else {
			gotoMain();
		}
		Utils.printOutToConsole(msg);
	}
	
	/**
	 * 进入 Main页面
	 */
	private void gotoMain(){
		if (isFirstIn) {
			startActivity(new Intent(getApplicationContext(), GuideActivity.class));
		} else {
			startActivity(new Intent(getApplicationContext(), MainActivity.class));
		}
		finish();
		
	}

	/**
	 * 获取登录状态及信息
	 */
	private void login() {
		if (!TextUtils.isEmpty(PreferencesUtils.getString(this, PreferencesUtils.USER_PHONE))
				&& !TextUtils.isEmpty(PreferencesUtils.getString(this,
						PreferencesUtils.USER_PASSWORD))) {
			mobile= PreferencesUtils.getString(this, PreferencesUtils.USER_PHONE);
			pwd= Crypto.decryptAES(
					PreferencesUtils.getString(this, PreferencesUtils.USER_PASSWORD),
					Crypto.PRIVATEKEY);

			RequestParams params = new RequestParams();
			params.addBodyParameter("username", mobile);
			params.addBodyParameter("password", pwd);

			onRequest(LOGIN, UrlConstant.LOGIN, HttpMethod.POST, params);
		} else {
			getRoot();
			checkVersion();
		}
	}

	private void getRoot() {
		onRequest(ROOT, UrlConstant.ROOTS, HttpMethod.GET, null);
	}

	private void checkVersion() {
		onRequest(GETLASTVERSION, UrlConstant.GETLASTVERSION, HttpMethod.GET, null);
	}

	@Override
	protected void setParams() {
		AppBasic.initDeviceId(this);
	}

	@Override
	protected void leftButton() {
	}

	@Override
	protected void rightButton() {
	}
}
